package main

import (
	"IEC104_Slave/app"
	"IEC104_Slave/config"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"time"
)

func main() {

	/**
	从接口取数
	*/
	go func() {
		return
		for {
			url := "http://localhost:7005/api/v1/systemManagementBiz/orgSiteEquipment/getPointData"
			method := "GET"
			client := &http.Client{}
			req, err := http.NewRequest(method, url, nil)

			if err != nil {
				fmt.Println(err)
				return
			}
			res, err := client.Do(req)
			if err != nil {
				fmt.Println(err)
				return
			}
			defer func(Body io.ReadCloser) {
				err := Body.Close()
				if err != nil {
					fmt.Println(err)
				}
			}(res.Body)

			body, err := ioutil.ReadAll(res.Body)
			if err != nil {
				fmt.Println(err)
				return
			}
			//fmt.Println(string(body))

			bodyMap := make(map[string]interface{})
			if err := json.Unmarshal(body, &bodyMap); err != nil {
				return
			}

			currentPoint := make(map[string]interface{})

			resPoint := bodyMap["data"].(map[string]interface{})
			for s := range resPoint {
				if resPoint[s] != nil && resPoint[s] != "" {
					currentPoint[s] = resPoint[s]
				}
			}
			config.CurrentData.Set(currentPoint)

			time.Sleep(10 * time.Second)
		}

	}()

	for {
		//启动配置的端口
		for _, port := range config.Cfg.Iec.Ports {

			if !config.ListenPortIsUse(port) {
				fmt.Printf("启动程序==>端口:%v\n", port)
				go app.CreateNewSlave(port)
			}
		}
		time.Sleep(5 * time.Second)
	}
}
